package com.lais.record.user.service;

import com.lais.record.common.utils.IdWorker;
import com.lais.record.user.constant.UserEnum;
import com.lais.record.user.constant.UserConstant;
import com.lais.record.user.domain.User;
import com.lais.record.user.exception.UserException;
import com.lais.record.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * @Author: luowen
 * @Description:
 * @Date: Create in 15:18 2019/11/30
 */
@Service
@Transactional
@SuppressWarnings("all")
@Slf4j
public class UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Value("${record.phone.code.prefix}")
    private String codePrefix;

    @Value("${record.default.user.avatar}")
    private String avatar;

    /**
     * 用户登录
     * @param phone
     * @param code
     * @return
     */
    public User login(String phone, String code) {
        log.info("userService login....");
        //1,获取key
        String key = codePrefix.concat(phone);
        //2，获取存储在redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(key);
        //3，比较验证码
        if(!StringUtils.equals(code,redisCode)){
            //验证码不等
            log.error("用户登录--验证码不匹配--手机号为：{}--系统验证码为：{}--用户验证码为：{}",phone,redisCode,code);
            throw new UserException(UserEnum.CODE_NOT_MATCH);
        }
        //验证码通过
        //4，根据手机号查询用户信息
        User user = this.findByPhone(phone);
        if(user == null){
            //说明用户未从登录过，第一次
            user = new User();
            user.setId(idWorker.nextId());
            user.setCreated(new Date());
            user.setAvatar(avatar);
            user.setPhone(phone);
            user.setStatus(UserConstant.UserStatus.EFFECTIVE);
            user.setNickname(phone);
            this.userMapper.insert(user);
        }
        return user;
    }

    public User findByPhone(String phone){
        log.info("根据手机号查询用户信息--phone:{}",phone);
        if(StringUtils.isEmpty(phone)){
            log.error("根据手机号查询用户信息--手机号不存在");
            throw new UserException(UserEnum.PHONE_NOT_EXIST);
        }
        User user = this.userMapper.findByPhone(phone);
        return user;
    }

    public User findByPhoneWithStatus(String phone,String status){
        log.info("根据手机号查询用户信息--phone:{}",phone);
        if(StringUtils.isEmpty(phone)){
            log.error("根据手机号查询用户信息--手机号不存在");
            throw new UserException(UserEnum.PHONE_NOT_EXIST);
        }
        User user = this.userMapper.findByPhone(phone);
        return user;
    }
}
